package com.xiaoqi.test;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int[] randomArry = random();
        //随机4个数
        int number = 0;
        while (number < 5) {
            number++;
            //让玩家输入4个数，有5次机会
            int[] guessArry = new int[4];
            for (int i = 0; i < guessArry.length; i++) {
                while (true) {
                    try {
                        System.out.println("请输入第" + (i + 1) + "个数字");
                        guessArry[i] = scan.nextInt();
                        for (int j = 0; j < i; j++) {
                            if (guessArry[i] == guessArry[j]) {
                                System.out.println("重复输入数字，请重新输入");
                                i--;
                            }
                        }
                        break;
                    } catch (Exception e) {
                        System.out.println("输入类型不对，重新输入");
                        scan.next();
                    }
                }
            }
//判断有几个A和几个B,A是位置和数字一样，B是有相同数字
            int a = 0;
            int b = 0;
            for (int i = 0; i < guessArry.length; i++) {
                if (randomArry[i] == guessArry[i]) {
                    a++;
                }
                for (int j = 0; j < guessArry.length; j++) {
                    if (guessArry[i] == randomArry[j]) {
                        b++;
                    }
                }
            }
            if (a == 4) {
                System.out.println("恭喜你猜对了");
                break;

            }
            if (number < 5) {
                System.out.println("你猜的是" + a + "A," + (b - a) + "B,你还有" + (5 - number) + "次机会");
            } else {
                System.out.println("游戏结束，很遗憾");
            }

        }


    }

    //随机生成4个号码的函数
    public static int[] random() {
        int[] arr = new int[4];
        boolean flag = true;
        while (flag) {
            //随机抓4个数
            for (int i = 0; i < arr.length; i++) {
                arr[i] = random(9, 0);//调用随机数
            }
            //判断4个数中是否有两两相等，有相等的n就自增
            int n = 0;
            for (int i = 0; i < arr.length; i++) {
                for (int j = i + 1; j < arr.length; j++) {
                    if (arr[i] == arr[j]) {
                        n++;
                    }
                }
            }
            // 如果没相等的n就保持不变为0，就结束while循环
            if (n == 0) {
                flag = false;
            }
        }
        return arr;

    }

    //根据范围随机生成一个数
    public static int random(int a, int b) {
        int ma = (int) (Math.random() * (a - b + 1) + b);
        return ma;
    }
}
